/*
 * Copyright (C) 2011 Niels Mayer <NielsMayer _AT_ gmail _DOT_ com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

import QtQuick 1.0
import QtWebKit 1.0

Rectangle {
    id:     root;
//  width:  480; height: 854; //Harmattan-sized in Portrait mode
    width:  854; height: 480; //Harmattan-sized in Landscape mode

    /* root.loading: Used to turn on/off BusyIndicator */
    property bool loading: false;

    SystemPalette { id:syspal }
    color:  syspal.window

    transitions: [
// NPM: this slow fade in of webView and fadeout of exampleChooser ends up being really slow on 
// ExoPC because the fadeout/in animation slows down the performance of the webrowser, which
// is CPU&Memory intensive while Exhibit is computing how to present its data.... Therefore let
// the browser do it's rendering while invisible and then show the completed result, rather than
// trying to composite the fade-in/out with the changing and updating browser....
//       Transition { from: "showExampleChooser"; to: "webViewBrowse";
//	     SequentialAnimation {         // start a slow fade as soon as you browse
//                       NumberAnimation { target: webView;        property: "opacity"; to: 1; duration: 2000 }
//                       NumberAnimation { target: exampleChooser; property: "opacity"; to: 0; duration: 2000 }}
//	 },
         Transition { from: "webViewBrowse";      to: "webViewReadySuccess";
	     ParallelAnimation {
                         NumberAnimation { target: webView;        property: "opacity"; to: 1; duration: 250; }
                         NumberAnimation { target: exampleChooser; property: "opacity"; to: 0; duration: 250; }}
         },
         Transition { from: "webViewReadySuccess"; to: "showExampleChooser";
             ParallelAnimation {
                         NumberAnimation { target: webView;        property: "opacity"; to: 0; duration: 250 }
                         NumberAnimation { target: exampleChooser; property: "opacity"; to: 1; duration: 250 }}
         }
    ]

    states: [
         State {
             name: "showExampleChooser"
             PropertyChanges { target: root; loading: false; }
             PropertyChanges { target: exampleChooser; focus: true;  visible: true;  opacity: 1; }
	     // When choosing examples, webview invisible and disabled
             PropertyChanges { target: webView;        focus: false; visible: false; opacity: 0; enabled: false; } 
         },
         State {
             name: "webViewBrowse"
             PropertyChanges { target: root;    loading: true; }
             PropertyChanges { target: exampleChooser; focus: false; visible: true;  opacity: 1; }
	     // On browsing, webView becomes enabled, stays invisible till ready
             PropertyChanges { target: webView;        focus: true;  visible: true;  opacity: 0; enabled: true; }
         },
         State {
             name: "webViewReadySuccess"
             PropertyChanges { target: root; loading: false; }
             PropertyChanges { target: exampleChooser; focus: false; visible: false; }
             PropertyChanges { target: webView;        focus: true;  visible: true;  }
         },
         State {
             name: "webViewReadyFailed"
             PropertyChanges { target: root; loading: false; }
             PropertyChanges { target: exampleChooser; focus: true;  visible: true;  opacity: 1; }
             PropertyChanges { target: webView;        focus: false; visible: false; opacity: 0; enabled: false; }
         }
     ]
     state: getInitialState(commandlineURL)            // global 'commandlineURL' set in qtzibit/main.cpp

    /* function to set initial state property */
    function getInitialState(file) {
        console.log("Calling getInitialState('" + file + "')");
	if (file == "") {
	    return('showExampleChooser');
	}
	else {
	    return(webViewBrowse(file));
	}
    }

    /* called from ExampleChooserDelegate: when example item clicked,
       browse the associated URL */
    function webViewBrowse(file) {
        console.log("Loading: " + file);
	webView.url   = file; //start loading URL, when finished webViewReady()  is called.
	webView.scale = 1.0;  //reset any zoom from previous browsing
	webView.sx    = 0;    //reset any x-scroll from previous browsing
	webView.sy    = 0;    //reset any y-scroll from previous browsing
        return (root.state = 'webViewBrowse');
    }

    /* called from FlickableWebView: on WebView's onLoadFinished
       signal. Show the WebView and stop the busy indicator after the page has
       loaded into WebView. */
    function webViewReady(successP) {
    	if (!successP && (root.state == 'webViewReadySuccess')) { //handle odd case where the same file first claims success, then failure.
	   console.log("Ignoring special case of success then failure: "  + webView.url);
	   root.state = 'webViewReadySuccess';
	}
        else if (successP) {
	   console.log("Loading Done: " + webView.url);
	   root.state = 'webViewReadySuccess';
	   webView.sy = -1;       //workaround to force webview repaint suggested by qt-components/desktop/examples/Browser.qml
                                  //sometimes, but not always, on stopping the spinner, a "hole" is left and wiggling the mouse
                                  //causes it to refresh the webview. This workaround seems to prevent that problem/bug.
	}
	else {
	   root.state = 'webViewReadyFailed';
	   console.log("Loading Failed: "  + webView.url);
	}
    }

    /* called from FlickableWebView: via WebView's javaScriptWindowObjects
       property.  when user clicks the "Browse Examples" links in the
       WebView, it shows the QML example chooser.  This is also a good demo of
       how to make calls back into QML from JavaScript. In HTML, when the
       user clicks an anchor defined as
       <a href="javascript:window.qml.showExampleChooser();">Browse Examples</a>
       this function will be called. */
    function showExampleChooser() {
        root.state = 'showExampleChooser';
    }

    ExhibitExamplesModel { id: exhibitExamples } //Static list of working HTML examples

    ListView {
        focus:				true;
        id:				exampleChooser;
        anchors.fill:			parent;
        clip:				true;
        model:				exhibitExamples;
        delegate:			ExampleChooserDelegate {}
        highlight:			Rectangle { color: "steelblue" }
        highlightMoveSpeed:		9999999;
        currentIndex:			-1;  //prevent it from defaulting to zero and causing the first item to appear selected
    }
    ScrollBar {        //from /opt/QtSDK/Demos/4.7/declarative/webbrowser/content/ScrollBar.qml
        scrollArea:			exampleChooser;
        height:				exampleChooser.height;
        width:				8;
        anchors.right:			exampleChooser.right
    }

    FlickableWebView {        //from /opt/QtSDK/Demos/4.7/declarative/webbrowser/content/FlickableWebView.qml
        id:                             webView
        visible:                        false
        anchors { top: parent.top; left: parent.left; right: parent.right; bottom: parent.bottom }
    }

    ScrollBar {               //from /opt/QtSDK/Demos/4.7/declarative/webbrowser/content/ScrollBar.qml
        scrollArea: webView; width: 8
        anchors { right: parent.right; top: parent.top; bottom: parent.bottom }
    }

    ScrollBar {               // from/opt/QtSDK/Demos/4.7/declarative/webbrowser/content/ScrollBar.qml
        scrollArea: webView; height: 8; orientation: Qt.Horizontal
        anchors { right: parent.right; rightMargin: 8; left: parent.left; bottom: parent.bottom }
    }
}
